
/**
 * 获取当前父、祖级滚动容器（overflow: auto, scroll）的元素
 * @param {Element|String} el 当前元素, 或者选择器
 * @return {Element} parentsEl 
 */
export const getScrollParent = (el) => {
    el = el instanceof HTMLElement ? el : document.querySelector(el);
    let _parent = el ? el.parentNode : null
    while(_parent) {
        const overflowVal = getComputedStyle(_parent)['overflow']
        const elIsScroll = ['auto', 'sroll'].includes(overflowVal)
        if (elIsScroll) {
            return _parent
        }

        // 重新赋值，继续查找
        _parent = _parent.parentNode
    }
    return null
}

/**
 * 加载图片
 * @param {String} src 
 * @return {Promise}
 */
export const imageLoad = src => {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.setSrc = (src) => {
            img.src = src
        }
        img.onload = resolve
        img.onerror = reject
        img.setSrc(src)
    })
}

/**
 * 防抖函数
 * @param {*} context 
 * @param {Function} fn 
 * @param {Number} wait 
 */
export const debounce = (context, fn, wait=300) => {
    let timer = null
    context = context || window
    return function (...args) {
        if (timer) {
            clearInterval(timer)
        }
        timer = setTimeout(() => {
            fn.apply(context, args) 
        }, wait);
    }
}